package com.piggy.oss.cloud;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.piggy.common.core.exception.base.BaseException;
import com.piggy.common.core.utils.SpringUtils;
import com.piggy.common.redis.service.RedisService;
import com.piggy.oss.config.BaiduOCRConfig;
import com.piggy.oss.constants.CloudConstants;
import com.piggy.oss.utils.Base64Util;
import com.piggy.oss.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 百度云识别
 */

@Slf4j
public class BaiduCloudService {
	private static RedisService redisCache;
	static {
		BaiduCloudService.redisCache =  SpringUtils.getBean(RedisService.class);
	}
	public String getBaiduCloudToken(){
		String baiduCloudVerifyKey="baidu_cloud_token:";

		//先判断缓存中是否有token
		if(StrUtil.isNotBlank(redisCache.getCacheObject(baiduCloudVerifyKey))){
			return redisCache.getCacheObject(baiduCloudVerifyKey);
		}

		//获取百度智能云的配置
		String ocrConfigJson = redisCache.getCacheObject(CloudConstants.SYS_CONFIG_KEY + CloudConstants.OCRCONFIG);
		if (StrUtil.isEmpty(ocrConfigJson))throw new BaseException("系统未配置云服务");

		BaiduOCRConfig ocrConfig = JSON.parseObject(ocrConfigJson, BaiduOCRConfig.class);
		// 获取token地址
		String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		String getAccessTokenUrl = authHost
			// 1. grant_type为固定参数
			+ "grant_type=client_credentials"
			// 2. 官网获取的 API Key
			+ "&client_id=" + ocrConfig.getApiKey()
			// 3. 官网获取的 Secret Key
			+ "&client_secret=" + ocrConfig.getSecretKey();
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.err.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			/**
			 * 返回结果示例
			 */
			log.info("result:" + result);
			JSONObject jsonObject = new JSONObject(result);
			String access_token = jsonObject.getString("access_token");
			redisCache.setCacheObject(baiduCloudVerifyKey, access_token, CloudConstants.BAIDUCLOUD_TOKEN_EXPIRATION, TimeUnit.MINUTES);
			return access_token;
		} catch (Exception e) {
			log.error("获取token失败！", e);
		}
		return null;
	}

	public String vatInvoice(MultipartFile file) {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice";
		try {
			// 本地文件路径
			//String filePath = "E:/znegzhifapiao.png";
//			byte[] imgData = FileUtil.readFileByBytes(filePath);
			byte[] imgData=file.getBytes();
			String imgStr = Base64Util.encode(imgData);
			String imgParam = URLEncoder.encode(imgStr, "UTF-8");
			String parmaType="image=";
			if(file.getOriginalFilename().contains(".pdf")){
				parmaType="pdf_file=";
			}
			String param = parmaType + imgParam;
			// 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
			//String accessToken = token.getAuth(API_KEY,SECRET_KEY);
			String result = HttpUtil.post(url, getBaiduCloudToken(), param);
//			System.out.println(result);
			return result;
		} catch (Exception e) {
			log.error("ocr识别失败！", e);
		}
		return null;
	}

	public String vatInvoice(String base64) {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice";
		try {
			return HttpUtil.post(url, getBaiduCloudToken(), base64);
		} catch (Exception e) {
			log.error("ocr识别失败！", e);
		}
		return null;
	}

	public String invoiceVerification(String param) {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice_verification";
		try {

			String result = HttpUtil.post(url, getBaiduCloudToken(), param);
//			System.out.println(result);
			return result;
		} catch (Exception e) {
			log.error("发票验真失败！", e);
		}
		return null;
	}

	public String businessLicense(String imgStr) {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license";
		try{
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
			String result = HttpUtil.post(url, getBaiduCloudToken(), "image=" + imgParam);
			cn.hutool.json.JSONObject yyJson = JSONUtil.parseObj(result);
			Object words_result = yyJson.get("words_result");
			cn.hutool.json.JSONObject wordsResultJson = JSONUtil.parseObj(words_result);
			Object shehuiCode = wordsResultJson.get("社会信用代码");
			cn.hutool.json.JSONObject shehuiJson = JSONUtil.parseObj(shehuiCode);
			Object words = shehuiJson.get("words");
			return words.toString().trim();
		}  catch (Exception e) {
			log.error("获取营业执照失败！", e);
		}
		return null;
	}

}
